﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.SessionState;
using System.Xml.Linq;
using System.Net;
using System.Net.Mail;
using SES.CMS.DO;
using SES.CMS.BL;
using System.Net.Configuration;

namespace SES.CMS
{
    public partial class ThanhToan : System.Web.UI.Page
    {
        private static DataTable dt = new DataTable();
        private static ClientLoginDO obj = new ClientLoginDO();
        private static int[] idgh = new int[100];
        private static float total;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                loadTT();
                loadGioHang();
                LoadThongTinThanhToan();
            }
        }

        public void loadTT()
        {
            Page.Title = "Gửi đơn hàng - Văn phòng phẩm Mỹ Đình";
            HttpSessionState ss = HttpContext.Current.Session;
            string session = ss.SessionID;

            if (Session["IDDN"] != null)
            {
                ClientLoginDO obj = new ClientLoginBL().Select(new ClientLoginDO { ClientLoginID = int.Parse(Session["IDDN"].ToString()) });
                txtDC.Text = obj.Address;
                txtEmail.Text = obj.Email;
                txtHT.Text = obj.ClientName;
                txtsdt.Text = obj.Mobile;
            }
        }

        protected void loadGioHang()
        {
            MasterPage mt = this.Master as MasterPage;
            Control uc = mt.FindControl("UcDanhMuc1") as Control;
            uc.Visible = true;
            Control uc2 = mt.FindControl("UcDanhMuc2") as Control;
            uc2.Visible = false;

            Page.Title = "Gửi đơn hàng - Văn phòng phẩm Mỹ Đình";
            
            DataTable tb = new DataTable();
            if (Session["GioHang"] != null)
            {
                tb = (DataTable)Session["GioHang"];
                dt.Clear();
                try
                {
                    dt.Columns.Add("STT");
                    dt.Columns.Add("SanPhamID");
                    dt.Columns.Add("TenSanPham");
                    dt.Columns.Add("HinhAnh");
                    dt.Columns.Add("SoLuong");
                    dt.Columns.Add("DonGia");
                    dt.Columns.Add("GiamGia");
                    dt.Columns.Add("ThanhTien");
                }
                catch { }

                int i = 0;
                foreach (DataRow dr in tb.Rows)
                {
                    cmsSanPhamDO obj = new cmsSanPhamBL().Select(new cmsSanPhamDO { SanPhamID = Int64.Parse(dr[1].ToString()) });
                    i++;
                    DataRow row = dt.NewRow();
                    row[0] = dr[0].ToString();
                    row[1] = dr[1].ToString();
                    row[2] = obj.TenSanPham;
                    row[3] = obj.HinhAnh;
                    row[4] = dr[2].ToString();
                    row[5] = obj.DonGia;
                    row[6] = obj.GiamGia;
                    row[7] = dr[3].ToString();
                    dt.Rows.Add(row);
                }

                if (dt.Rows.Count > 0)
                {
                    GridGioHang.DataSource = dt;
                    GridGioHang.DataBind();
                    float sum = 0;
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        sum += float.Parse(dt.Rows[j].ItemArray[7].ToString());
                    }
                    lblSum.Text = "Tổng: <span style='color:red;font-weight:bold;'>" + sum.ToString("##,## VNÐ") + "</span>";
                    lbThanhTien.Text = "Tổng: <span style='color:green;font-weight:bold;'>" + NumberToStringVN.DocTienBangChu((decimal)sum, " đồng") + "</span";
                }
            }
            else
            {
                lbThanhTien.Text = "Chưa có sản phẩm nào trong giỏ hàng";
                lblSum.Text = "";
            }
        }

        public void LoadThongTinThanhToan()
        {
            lblThongTinThanhToan.Text = new sysConfigBL().Select(new sysConfigDO { ConfigID = 13 }).ConfigValue;
        }

        public cmsGioHangDO init()
        {
            HttpSessionState ss = HttpContext.Current.Session;
            string session = ss.SessionID;

            
            cmsGioHangDO objGioHang = new cmsGioHangDO();
            if (Session["IDDN"] != null)
            {
                obj = new ClientLoginBL().Select(new ClientLoginDO { ClientLoginID = int.Parse(Session["IDDN"].ToString()) });
            }
            else
            {
                obj.ClientLoginID = 0;
                obj.ClientName = txtHT.Text;
                obj.Email = txtEmail.Text;
                obj.Mobile = txtsdt.Text;
                obj.Address = txtDC.Text;
            }
            objGioHang.ClientLoginID = obj.ClientLoginID;
            objGioHang.HinhThucThanhToan = txtHTTT.Text;
            objGioHang.NgayDatHang = DateTime.Now;
            objGioHang.SessionID = session;
            objGioHang.XuLy = false;

            //objDonHang.HoTen = obj.ClientName;
            //objDonHang.GhiChu = txtGC.Text;
            //objDonHang.HTTT = txtHTTT.Text;
            //objDonHang.SDT = obj.Mobile;
            //objDonHang.Email = obj.Email;
            //objDonHang.SessionID = session;
            //objDonHang.DiaChi = obj.Address;
            //objDonHang.DiaChiGiaoHang = txtDCGH.Text;
            //objDonHang.UserID = obj.ClientLoginID;

            return objGioHang;
        }
        public static String Address
        {
            get
            {
                SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                return cfg.Network.UserName;
            }
        }
        public static String Pass
        {
            get
            {
                SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                return cfg.Network.Password;
            }
        }
        public void sendsMail(String name, String bd, string title)
        {
            string i = DateTime.Now.ToString();
            sysConfigDO cmsConfig = new sysConfigDO();
            int id = 4;

            cmsConfig = new sysConfigBL().Select(new sysConfigDO { ConfigID = 4 });

            SmtpClient SmtpServer = new SmtpClient();
            SmtpServer.Credentials = new System.Net.NetworkCredential(Address, Pass);
            SmtpServer.Port = 587;
            SmtpServer.Host = "Smtp.gmail.com";
            SmtpServer.EnableSsl = true;
            MailMessage mail = new MailMessage();
            String addr = cmsConfig.ConfigValue.ToString();

            try
            {
                mail.From = new MailAddress(addr, name, System.Text.Encoding.UTF8);
                mail.To.Add(addr);
                mail.Subject = title;
                mail.Body = bd;
                mail.IsBodyHtml = true;
                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                SmtpServer.Send(mail);
            }
            catch (Exception ex)
            {
            }
        }
        protected void btn_Click(object sender, EventArgs e)
        {
            cmsGioHangDO objGioHang = init();
            foreach (DataRow dr in dt.Rows)
            {
                objGioHang.SanPhamID = Int64.Parse(dr[1].ToString());
                objGioHang.SoLuong = Int32.Parse(dr[4].ToString());
                objGioHang.NgayGiaoHang = DateTime.Now;
                objGioHang.ThanhTien = float.Parse(dr[7].ToString());
                int kq = new cmsGioHangBL().Insert(objGioHang);
                if (kq > 0)
                {
                    cmsDonHangDO objDonHang = new cmsDonHangDO();
                    objDonHang.DiaChiGiaoHang = txtDCGH.Text;
                    objDonHang.DiaChi = obj.Address;
                    objDonHang.Email = obj.Email;
                    objDonHang.GhiChu = txtGC.Text;
                    objDonHang.GioHangID = kq;
                    objDonHang.HoTen = obj.ClientName;
                    objDonHang.HTTT = txtHTTT.Text;
                    objDonHang.SDT = obj.Mobile;
                    objDonHang.SessionID = objGioHang.SessionID;
                    objDonHang.TongTien = objGioHang.ThanhTien;
                    objDonHang.UserID = obj.ClientLoginID;
                    objGioHang.XuLy = true;

                    kq = new cmsDonHangBL().Insert(objDonHang);
                    objDonHang.XuLy = true;

                    new cmsGioHangBL().Update(objGioHang);
                    Session["GioHang"] = null;
                    try
                    {
                        string body = "Chào bạn, bạn nhận được email này vì đã tiến hành đặt hàng trên website http://vanphongphammydinh.vn. Chúng tôi sẽ liên hệ với bạn trong thời gian sớm nhất.";
                        sendsMail(objDonHang.HoTen, body,"Đơn đặt hàng vanphongphammydinh.vn" + kq);
                    }
                    catch { }

                    Ultility.Alert("Bạn đã đặt hàng thành công!!", "/Default.aspx");
                }
                
            }



            //cmsDonHangDO objDonHang = init();
            //DataTable dt = new cmsGioHangBL().SelectBySessionChuaXL(objDonHang.SessionID);
            //Int64 tong = 0;
            //foreach (DataRow dr in dt.Rows)
            //{
            //    objDonHang.GioHangID = int.Parse(dr[0].ToString());
            //    tong += Int64.Parse(dr[6].ToString());
            //    cmsGioHangDO obj = new cmsGioHangBL().Select(new cmsGioHangDO { GioHangID = objDonHang.GioHangID });
            //    obj.XuLy = true;
            //    obj.NgayGiaoHang = DateTime.Parse(txtNgayGiaoHang.Text);
            //    new cmsGioHangBL().Update(obj);
            //}
            
            //objDonHang.XuLy = false;
            //objDonHang.TongTien = tong;
            //new cmsDonHangBL().Insert(objDonHang);

            //Ultility.Alert("Bạn đã đặt hàng thành công!!", "/Default.aspx");
        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {
            Response.Redirect("/GioHang.aspx");
        }

        /* Giỏ hàng*/
        

        protected void GridGioHang_RowCommand(object sender, GridViewCommandEventArgs e)
        {
        }

        protected void GridGioHang_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {

        }

        protected void GridGioHang_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    //float lbsum = 0;
                    //foreach (GridViewRow dr in GridGioHang.Rows)
                    //{
                    //    lbsum += (float)int.Parse(dr.Cells[5].ToString());
                    //}
                    
                }

                if (e.Row.RowType == DataControlRowType.Footer)
                {
                }
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Attributes.Add("style", "background-color: #FFFFFF; color: black;");
                    e.Row.Attributes.Add("onmouseover", "style.backgroundColor='#DEE0BF'");
                    e.Row.Attributes.Add("onmouseout", "style.backgroundColor='#FFFFFF'");
                }
            }
            //catch { }

        }

        protected void btnCapNhat_Click(object sender, EventArgs e)
        {
            //cmsGioHangDO obj = new cmsGioHangDO();
            //for (int i = 0; i < GridGioHang.Rows.Count; i++)
            //{
            //    TextBox lbSL = (TextBox)GridGioHang.Rows[i].FindControl("txtSL");
            //    //int valuuu = (int)GridGioHang[i, 2].Value;
            //    obj = new cmsGioHangBL().Select(new cmsGioHangDO { GioHangID = Int64.Parse(GridGioHang.DataKeys[i].Value.ToString()) });
            //    try
            //    {
            //        obj.SoLuong = int.Parse(lbSL.Text);
            //    }
            //    catch { }
            //    new cmsGioHangBL().Update(obj);
            //}
            //loadGioHang();
        }

        protected void GridGioHang_DataBinding(object sender, System.EventArgs e)
        {
            //Label pLabel = (Label)sender;
            //int dItemPrice = (Eval("ThanhTien") != DBNull.Value) ? (int)(Eval("ThanhTien")) : 0;
            //pLabel.Text = dItemPrice.ToString("0.00");
            //tong += dItemPrice; // This will add to running total of all.
        }

        protected void GridGioHang_DataBound(object sender, EventArgs e)
        {

        }

    }
}
